package com.htthorizon.system.excel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.listener.ReadListener;
import com.htthorizon.system.api.domain.SysDept;
import com.htthorizon.system.api.domain.SysUser;
import com.htthorizon.system.excel.excel.UserExcel;
import com.htthorizon.system.service.ISysDeptService;
import com.htthorizon.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author Brilliant
 */
@Component
public class UserExcelUploadListener extends AnalysisEventListener<UserExcel> {

    private static final int BATCH_SIZE = 1000;

    private final List<SysUser> memory=new ArrayList<>(BATCH_SIZE);

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysDeptService sysDeptService;



    @Override
    public void invoke(UserExcel userExcel, AnalysisContext analysisContext) {
        SysUser sysUser = this.userExcel2SysUser(userExcel);
        memory.add(sysUser);
        this.benchInsert(memory);
    }

    private void benchInsert(List<SysUser> memory) {
        if (memory.size()>=BATCH_SIZE){
          int result=  sysUserService.banchSave(memory);
            memory.clear();
        }
    }

    private SysUser userExcel2SysUser(UserExcel userExcel){
        SysUser sysUser = new SysUser();
        sysUser.setUserName(userExcel.getUserName());
//        sysUse;.setPassword("$2a$10$gybG43dgzj08AqGs.0fZnOIhhrnR3AROfS2hnL7iARgp2nmtcRlPa");
        sysUser.setNickName(userExcel.getNickName());
        sysUser.setSex(this.gender2Sex(userExcel.getGender()));
        SysDept sysDept = Optional.ofNullable(sysDeptService.getDeptByName(userExcel.getDataScope())).orElse(new SysDept());
        sysUser.setDept(sysDept);
        sysUser.setDeptId(sysDept.getDeptId());
        sysUser.setStatus("0");
        return sysUser;
    }

    private String gender2Sex(String gender) {
        if ("男".equals(gender)){
            return "0";
        }
        return "1";
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        int result=  sysUserService.banchSave(memory);
        memory.clear();
    }
}
